package net.tv90.auth.service.impl;

import jakarta.servlet.http.HttpServletRequest;
import net.tv90.auth.dao.AccountMapper;
import net.tv90.auth.dao.UserMapper;
import net.tv90.auth.exception.AuthException;
import net.tv90.auth.model.SMSCode;
import net.tv90.auth.model.domain.Account;
import net.tv90.auth.model.domain.User;
import net.tv90.auth.model.dto.RegistrationByEmailDTO;
import net.tv90.auth.model.vo.UserLoginVO;
import net.tv90.auth.service.RegisterService;
import net.tv90.auth.service.SMSCodeService;
import net.tv90.auth.utils.IpUtils;
import net.tv90.auth.utils.TokenUtils;
import net.tv90.auth.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    SMSCodeService smsCodeService;

    @Autowired
    UserUtils userUtils;

    @Autowired
    TokenUtils tokenUtils;

    @Override
    @Transactional
    public UserLoginVO registerByEmail(RegistrationByEmailDTO dto, HttpServletRequest request) {
        boolean checkCode = smsCodeService.checkCodeForEmail(new SMSCode(dto.getEmail(), dto.getSmsCode()));
        if (!checkCode) {
            throw new AuthException("邮箱验证码错误", "email");
        }

        Integer checkUser = accountMapper.checkUserExistByUserName(dto.getUsername());
        if (checkUser != 0) {
            throw new AuthException("用户已被注册", "username");
        }

        Integer checkEmail = accountMapper.checkUserExistByEmail(dto.getEmail());
        if (checkEmail != 0) {
            throw new AuthException("邮箱已被注册", "email");
        }

        //成功
        Account account = Account.builder()
                .username(dto.getUsername())
                .password(dto.getPassword())
                .email(dto.getEmail())
                .createIp(IpUtils.getIpAddr(request))
                .createTime(LocalDateTime.now())
                .lastLoginTime(LocalDateTime.now())
                .lastLoginIp(IpUtils.getIpAddr(request))
                .loginTimes(0)
                .status(0)
                .build();
        accountMapper.insert(account);

        User user = User.builder()
                .nickname(dto.getUsername())
                .lastUpdateTime(LocalDateTime.now())
                .build();
        userMapper.insert(user);

        String token = tokenUtils.generateToken(account.getUsername(), account.getPassword());
        userUtils.login(account.getUsername(), token);

        return new UserLoginVO(account.getUsername(), user.getNickname(), user.getAvatar(), token);
    }
}
